package com.edgclub.edg.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.BBAdapter;
import com.edgclub.edg.adapter.adapteruitls.MyItemClickListener;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.AaskBeanData;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.Topic;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.TopicBBData;
import com.edgclub.edg.model.result.TopicListData;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.squareup.otto.ThreadEnforcer;

import java.util.ArrayList;

public class OtherUserBBFragment extends GzBaseFragment implements View.OnClickListener, BBAdapter.LikeClickListener {

    private Activity mActivity;
    private User otherUser;

    private int currPage = 1;
    private int pageSize = 20;
    private XRecyclerView recyclerView;
    private BBAdapter bbAdapter;
    private ArrayList<Topic> topicList;

    private UserPrefUtils userPrefUtils;
    private TopicApi topicApi;

    private boolean isFirstLoad = true;
    private int type;
    private TextView text_empty;
    private ImageView imageView_empty;
    private LinearLayout layout_empty;


    public static OtherUserBBFragment newInstance(User otherUser,int type) {
        OtherUserBBFragment f = new OtherUserBBFragment();
        Bundle args = new Bundle();
        args.putSerializable("user", otherUser);
        args.putInt("type",type);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mActivity = this.getActivity();
        return inflater.inflate(R.layout.fragment_bb, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        otherUser = (User) getArguments().getSerializable("user");
        type=getArguments().getInt("type",0);
        if(null==otherUser)otherUser=new User();

        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).register(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (recyclerView != null && isFirstLoad) {
                isFirstLoad = false;
                recyclerView.setRefreshing(true);
            }

        } else {
            if (bbAdapter != null && bbAdapter.getMediaPlayerUtil() != null) {
                stopMediaPlayer();
            }
        }
    }

    @Override
    public void onPause() {
        stopMediaPlayer();
        super.onPause();
    }

    private void initView(View view) {
        initLoadView(view);
        recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getEdg(currPage);
            }

            @Override
            public void onLoadMore() {
                getEdg(currPage);
            }
        });
        layout_empty= (LinearLayout) view.findViewById(R.id.layout_empty);;
        text_empty= (TextView) view.findViewById(R.id.text_empty);;
        imageView_empty = (ImageView) view.findViewById(R.id.imageView_empty);
        imageView_empty.setVisibility(View.VISIBLE);
        if (type==0) {
            imageView_empty.setImageResource(R.drawable.nomess);
            text_empty.setText("还没有发过任何帖子");
        }else{
            imageView_empty.setImageResource(R.drawable.nomess);
            text_empty.setText("还没有收藏过任何帖子");
        }
    }

    private void initData() {
        topicApi = new TopicApi(getActivity());
        userPrefUtils = new UserPrefUtils(getActivity());
        topicList = new ArrayList<>();

        bbAdapter = new BBAdapter(getActivity());
        bbAdapter.setDatas(topicList);
        bbAdapter.setLikeClickListener(this);
        bbAdapter.setVisableDelet(true);
        recyclerView.setAdapter(bbAdapter);

            isFirstLoad = false;
        getEdg(currPage);

        bbAdapter.setOnItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                bbAdapter.jumpTopicDetailActivity(postion);
            }
        });
        bbAdapter.setCancleCollectionPostListener(new BBAdapter.cancleCollectionPostListener() {
            @Override
            public void cancleCollectionPost(int position) {
                delCollection(position);
            }
        });

    }
    private void delCollection(int p) {
        if (edgLoading) {
            return;
        }
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicList.get(p).getPostsId());
        postsParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.cancleCollectionPost(postsParam,new getcancleListener(p));
    }
    private boolean edgLoading = false;
    private boolean isEdgEnd = false;

    private void getEdg(int page) {
        if (edgLoading || isEdgEnd) {
            return;
        }
        User user = userPrefUtils.getUser();
        PostsParam nearbyParam = new PostsParam();
        nearbyParam.setPage(page + "");
        nearbyParam.setPageSize(pageSize + "");
        nearbyParam.setUserId(user.getId() + "");
        nearbyParam.setToUserId(otherUser.getId());
        if(type==0)
            topicApi.getUserPosts(nearbyParam,new getedgListener(""));
        else
            topicApi.myCollection(nearbyParam,new getedgListener(""));

    }




    private void likePost(String topicId) {
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.likePost(postsParam, new getlikeListener());
    }

    private void unlikePost(String topicId) {
        PostsParam postsParam = new PostsParam();
        postsParam.setPostsId(topicId);
        postsParam.setUserId(userPrefUtils.getUser().getId() + "");
        topicApi.unlikePost(postsParam, new getlikeListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_refresh:
                break;

        }
    }

    private void stopMediaPlayer() {
        if (bbAdapter.getMediaPlayerUtil().isPlaying()) {
            bbAdapter.getMediaPlayerUtil().stopPlayVoice();
            bbAdapter.notifyDataSetChanged();
        }
    }



    @Override
    public void like(int position) {
        Topic topic = topicList.get(position);
        if ("1".equals(topic.getLiked())) {
            unlikePost(topic.getPostsId());
            topic.setLiked("0");
        } else {
            likePost(topic.getPostsId());
            topic.setLiked("1");
        }
        bbAdapter.notifyDataSetChanged();
    }
    class getcancleListener implements VolleyListener {

        int type;

        public getcancleListener(int type) {
            this.type = type;
        }

        @Override
        public void onStart(String tag) {
            edgLoading = true;
        }

        @Override
        public void onSuccess(String response, String tag) {
            edgLoading = false;
            if (JSONHelper.isSuccess(response)) {
               topicList.remove(type);
                bbAdapter.notifyDataSetChanged();
            } else {

            }

        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }
    class getedgListener implements VolleyListener {

        String type;

        public getedgListener(String type) {
            this.type = type;
        }

        @Override
        public void onStart(String tag) {
            edgLoading = true;
        }

        @Override
        public void onSuccess(String response, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setLoadViewGONE();
            if (JSONHelper.isSuccess(response)) {
                if(tag.equals(ApiConfig.APIURL.URL_POSTS_USER_POSTS)) {
                    ArrayList<Topic> topics = null;
                    TopicBBData data = JsonUtil.getMode(response,
                            TopicBBData.class);
                    if (null != data) {
                        topics = data.getData().getPosts();
                        if (topics != null && topics.size() > 0) {
                            if (currPage == 1) {
                                topicList.clear();
                            }
                            //分离图片语音
                            for(int i=0;i<topics.size();i++){
                                Topic topic = topics.get(i);
                                ArrayList<PostsAlbum> audios = new ArrayList<>();
                                ArrayList<PostsAlbum> albums = new ArrayList<>();
                                final ArrayList<PostsAlbum> tmpalbums = topic.getAlbums();
                                if (tmpalbums != null && tmpalbums.size() > 0) {
                                    for (PostsAlbum postsAlbum : tmpalbums) {
                                        if (postsAlbum.getUrl().contains(
                                                BBConstant.URL_VOICE_PROTOCOL)) {
                                            audios.add(postsAlbum);
                                        }else{
                                            albums.add(postsAlbum);
                                        }
                                    }
                                }
                                topic.setAlbums(albums);
                                topic.setAudios(audios);
                            }
                            topicList.addAll(topics);
                            currPage++;
                            bbAdapter.setDatas(topicList);
                            bbAdapter.notifyDataSetChanged();
                        }else{
                            recyclerView.noMoreLoading();
                        }
                    }
                }else if(tag.equals(ApiConfig.APIURL.URL_POSTS_MY_COLLECTION)){
                    ArrayList<Topic> topics = null;
                    TopicListData data = JsonUtil.getMode(response,
                            TopicListData.class);
                    if (null != data) {
                        topics = data.getData();
                        if (topics != null && topics.size() > 0) {
                            if (currPage == 1) {
                                topicList.clear();
                            }

                            //分离图片语音
                            for(int i=0;i<topics.size();i++){
                                Topic topic = topics.get(i);
                                ArrayList<PostsAlbum> audios = new ArrayList<>();
                                ArrayList<PostsAlbum> albums = new ArrayList<>();
                                final ArrayList<PostsAlbum> tmpalbums = topic.getAlbums();
                                if (tmpalbums != null && tmpalbums.size() > 0) {
                                    for (PostsAlbum postsAlbum : tmpalbums) {
                                        if (postsAlbum.getUrl().contains(
                                                BBConstant.URL_VOICE_PROTOCOL)) {
                                            audios.add(postsAlbum);
                                        }else{
                                            albums.add(postsAlbum);
                                        }
                                    }
                                }
                                topic.setAlbums(albums);
                                topic.setAudios(audios);
                            }
                            topicList.addAll(topics);
                            currPage++;
                            bbAdapter.setDatas(topicList);
                            bbAdapter.notifyDataSetChanged();
                        }else{
                            recyclerView.noMoreLoading();
                        }
                    }
                }
            } else {

            }


            if (!"".equals(topicList)&&topicList.size()>0){
                layout_empty.setVisibility(View.GONE);
                recyclerView.setPullRefreshEnabled(true);
            }
            else {
                layout_empty.setVisibility(View.VISIBLE);
                recyclerView.setPullRefreshEnabled(false);
            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
            recyclerView.refreshComplete();
            recyclerView.loadMoreComplete();
            setNoNetWork(new ReLoadClickListener() {
                @Override
                public void reload() {
                    getEdg(currPage);
                }
            });
            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }


    class getlikeListener implements VolleyListener {

        @Override
        public void onStart(String tag) {
        }

        @Override
        public void onSuccess(String response, String tag) {
            if (JSONHelper.isSuccess(response)) {
                if (tag.equals((ApiConfig.APIURL.URL_POSTS_LIKE))) {
                    AaskBeanData aaskBeanData = JsonUtil.getMode(response, AaskBeanData.class);
                    if (null != aaskBeanData && aaskBeanData.getTaskData().size() > 0) {
                        for (AaskBeanData.AaskBean bean : aaskBeanData.getTaskData()) {
                            StringUtils.postToast2(getActivity(), bean.getName() + "", bean.getGold() + "");
                        }
                    }
                } else if (tag.equals((ApiConfig.APIURL.URL_POSTS_UNLIKE))) {

                }
            } else {

            }
        }

        @Override
        public void onFaile(VolleyError volleyError, String tag) {
            edgLoading = false;
//            ResultCode.toastVolleyError(getActivity(), volleyError);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
                ThreadEnforcer.MAIN).unregister(this);
    }

}
